import FilterForm from "@/views/Board/Pdca/components/FilterForm.jsx";
import FilterToolBar from "@/components/filter-tool-bar";
import TableData from "./components/TableData";
import { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { getFirstDayOfMonth, getLastDayOfMonth } from '@/utils/time';
import { addTab } from '@/store/modules/tabListSlice';
import dayjs from 'dayjs';
import api from '@/api';
import { useDispatch } from "react-redux";
import { message } from "antd";

const DATASET_IDS = {
  PROJECT: 14,
  LANGUAGE: 20,
  TYPE: 16,
};

const Pdca = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const filterFormRef = useRef(null);

  // 合并相关状态
  const [state, setState] = useState({
    filter: {
      status: null,
      project_id: null,
      type_id: null,
      language_id: null,
      mark: null,
      content: "",
      taskTime: [dayjs(getFirstDayOfMonth()), dayjs(getLastDayOfMonth())],
    },
    options: {
      projectList: [],
      languageList: [],
      typeList: [],
    },
    tableData: [],
    selectList: [],
  });

  // 提取状态更新函数
  const updateState = useCallback((key, value) => {
    setState(prev => ({ ...prev, [key]: value }));
  }, []);

  // 统一的数据初始化函数
  const initDataList = useCallback(async () => {
    try {
      const [projectRes, languageRes, typeRes] = await Promise.all([
        api.dataset.getChildrenById({ id: DATASET_IDS.PROJECT }),
        api.dataset.getChildrenById({ id: DATASET_IDS.LANGUAGE }),
        api.dataset.getChildrenById({ id: DATASET_IDS.TYPE }),
      ]);

      const formatData = (data) => [
        { id: null, value: '全部' },
        ...data.map(item => ({ id: item.id, value: item.name }))
      ];

      updateState('options', {
        projectList: formatData(projectRes.data),
        languageList: formatData(languageRes.data),
        typeList: formatData(typeRes.data),
      });
    } catch (error) {
      message.error('初始化数据失败');
    }
  }, [updateState]);

  // 搜索处理函数
  const handleSearch = useCallback(async () => {
    try {
      const form = { ...state.filter };
      const taskTime = form.taskTime || [null, null];
      const params = {
        ...form,
        start_on: taskTime[0],
        finish_on: taskTime[1],
      };

      const res = await api.board.list(params);
      updateState('tableData', res.data.map(item => ({ ...item, key: item.id })));
    } catch (error) {
      message.error('获取数据失败');
    }
  }, [state.filter, updateState]);

  // 重置处理函数
  const handleReset = useCallback(() => {
    filterFormRef.current?.resetFields();
    updateState('filter', {
      status: null,
      project_id: null,
      type_id: null,
      language_id: null,
      mark: null,
      content: "",
      taskTime: [dayjs(getFirstDayOfMonth()), dayjs(getLastDayOfMonth())],
    });
  }, [updateState]);

  // 删除处理函数
  const handleDelete = useCallback(async (rows) => {
    try {
      await api.board.delete(Array.isArray(rows) ? rows : [rows]);
      message.success("删除成功");
      handleSearch();
      updateState('selectList', []);
    } catch (error) {
      message.error('删除失败');
    }
  }, [handleSearch, updateState]);

  // 状态更新处理函数
  const handleStatusUpdate = useCallback(async (row, updates) => {
    try {
      const updatedRow = {
        ...row,
        ...updates,
      };
      delete updatedRow.key;
      await api.board.update(updatedRow);
      handleSearch();
    } catch (error) {
      message.error('更新失败');
    }
  }, [handleSearch]);

  // 完成状态处理
  const changeFinishStatus = useCallback((row, type) => {
    const updates = {
      finish_on: type === 'finish' ? dayjs().format('YYYY-MM-DD') : null,
      status: type === 'finish' ? 2 : 1,
    };
    handleStatusUpdate(row, updates);
  }, [handleStatusUpdate]);

  // 收藏状态处理
  const handleUpdateMarkStatus = useCallback((row) => {
    const updates = { mark: row.mark === 0 ? 1 : 0 };
    handleStatusUpdate(row, updates);
  }, [handleStatusUpdate]);

  // 路由跳转处理
  const navigateToPath = useCallback((path, title) => {
    const tabConfig = {
      path,
      title,
      readonly: false,
    };
    dispatch(addTab(tabConfig));
    navigate(path);
  }, [dispatch, navigate]);

  // 编辑处理
  const handleEdit = useCallback((row) => {
    if (row) {
      navigateToPath(
        `/board/pdca/edit?id=${row.id}`,
        `编辑任务ID${row.id}`
      );
    } else {
      const projectId = state.filter.project_id;
      const path = `/board/pdca/edit${projectId ? '?projectId=' + projectId : ''}`;
      navigateToPath(path, '新建任务');
    }
  }, [navigateToPath, state.filter.project_id]);

  // 报告处理
  const handleReport = useCallback((type) => {
    if (!state.filter.project_id) {
      message.warning("请先选择项目");
      return;
    }
    const path = `/board/pdca/report?type=${type}${state.filter.project_id ? '&projectId=' + state.filter.project_id : ''}`;
    navigateToPath(path, `创建${type === 'daily' ? '日' : '月'}报`);
  }, [navigateToPath, state.filter.project_id]);

  // 按钮配置
  const btnGroup = useMemo(() => [
    [
      { text: '新增', type: 'primary', action: 'handleAdd' },
      { text: '批量删除', type: 'primary', danger: true, action: 'handleBatchDel' },
      { text: '创建日报', type: 'primary', action: 'handleDailyReport' },
      { text: '创建月报', type: 'primary', action: 'handleMonthReport' },
    ],
    [
      { text: '查询', type: 'primary', action: 'handleSearch' },
      { text: '重置', type: 'default', action: 'handleReset' },
    ]
  ], []);

  // 初始化数据
  useEffect(() => {
    initDataList();
  }, [initDataList]);

  // 监听筛选条件变化
  useEffect(() => {
    handleSearch();
  }, [state.filter, handleSearch]);

  return (
    <div>
      <FilterForm
        initialValues={state.filter}
        setFilterForm={(filter) => updateState('filter', filter)}
        filterOptions={state.options}
        ref={filterFormRef}
        className='pdca-filter-form'
      />
      <FilterToolBar 
        btnGroup={btnGroup} 
        handleSearch={handleSearch} 
        handleReset={handleReset} 
        handleAdd={() => handleEdit()}
        handleBatchDel={() => handleDelete(state.selectList)}
        handleDailyReport={() => handleReport('daily')}
        handleMonthReport={() => handleReport('month')}
      />
      <TableData 
        data={state.tableData} 
        handleDel={handleDelete} 
        handleUpdateMarkStatus={handleUpdateMarkStatus} 
        handleEdit={handleEdit}
        setSelectList={(selectList) => updateState('selectList', selectList)}
        changeFinishStatus={changeFinishStatus}
      />
    </div>
  );
};

export default Pdca;
